import java.lang.reflect.Field;
import java.lang.reflect.Method;
import java.util.Iterator;
import java.util.Vector;

/**
 * @author zhuyunhui 2020-06-18
 */
public class TestLoad {
    public static void main(String[] args) {
        System.out.println("load");
        System.load("/Users/jonny/code/self-workspace/install-ren-exercise/agent-module/src/main/resources/async-profiler/libasyncProfiler-mac-x64.so");
        System.out.println("===");
        System.load("/Users/jonny/code/self-workspace/install-ren-exercise/agent-module/src/main/resources/async-profiler/libasyncProfiler-mac-x64.so");
        unloadAllNativeLibs();
        System.out.println("ok");
    }

    public static synchronized void unloadAllNativeLibs() {
        try {
            ClassLoader classLoader = TestLoad.class.getClassLoader();
            Field field = ClassLoader.class.getDeclaredField("nativeLibraries");
            field.setAccessible(true);
            Vector<Object> libs = (Vector<Object>) field.get(classLoader);
            Iterator it = libs.iterator();
            while (it.hasNext()) {
                Object object = it.next();
                Method finalize = object.getClass().getDeclaredMethod("finalize");
                finalize.setAccessible(true);
                finalize.invoke(object);
            }
        } catch (Throwable th) {
            th.printStackTrace();
        }
    }

}
